package com.educate.common.web;


import lombok.extern.log4j.Log4j2;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Log4j2
public class JSessionIdUtils {

    public static final String JSESSIONID = "JSESSIONID";

    public static String getJSessionId() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getRequest();
//        request.getSession();
        Cookie cookie = WebUtils.getCookie(request, JSESSIONID);
        if (cookie == null) {
            HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder
                    .getRequestAttributes()).getResponse();
            cookie = new Cookie(JSESSIONID, IdGen.uuid());
            cookie.setHttpOnly(true);
            cookie.setMaxAge(Integer.MAX_VALUE);
            cookie.setPath("/");
            response.addCookie(cookie);
            log.debug("JSessionIdUtils.createJSessionId = " + cookie.getValue());
        } else {
            log.debug("JSessionIdUtils.getJSessionId = " + cookie.getValue());
        }
        return cookie.getValue();
    }
}
